將額外權責動態附加於物件身上,不必衍生子類別即可彈性增廣功能
class Component
def operation
raise NotImplementedError, "#{self.class} has not implemented method '#{__method__}'"
end
end
class ConcreteComponent < Component
def operation
'ConcreteComponent'
end
end
class Decorator < Component
attr_accessor :component
def initialize(component)
@component = component
end
def operation
@component.operation
end
end
class ConcreteDecoratorA < Decorator
def operation
"ConcreteDecoratorA(#{@component.operation})"
end
end
class ConcreteDecoratorB < Decorator
def operation
"ConcreteDecoratorB(#{@component.operation})"
end
end
def client_code(component)
print "RESULT: #{component.operation}"
end
simple = ConcreteComponent.new
puts 'Client: I\'ve got a simple component:'
client_code(simple)
puts "\n\n"
decorator1 = ConcreteDecoratorA.new(simple)
decorator2 = ConcreteDecoratorB.new(decorator1)
puts 'Client: Now I\'ve got a decorated component:'
client_code(decorator2)
這裡之所以不用繼承的原因在於,過多的組合會產出太多子類別繼承,而且繼承是屬於靜態(無法在過程中改變物件行為)所以使用組合方式進行
文章不定期更新!(umm ... 最近比較忙碌所以沒辦法紀錄太多,但會在之後陸續補充與將內容完整
感謝大家 如有問題,再煩請大家指教!